package com.qyhl.webtv.module_broke.scoop.addscoop;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;
import androidx.core.view.MotionEventCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.broke.ScoopTopicBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.AddPictureView.GridImageView;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.qyhl.webtv.module_broke.R;
import com.qyhl.webtv.module_broke.R2;
import com.qyhl.webtv.module_broke.utils.view.RulePopup;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;


/**
 * Created by qyhl on 2017/12/11.
 *
 * @author qyhl
 * 添加图文爆料
 */

@Route(path = ARouterPathConstant.SCOOP_ADD_PIC)
public class ScoopAddPictureActivity extends BaseActivity implements ScoopAddContract.ScoopAddView {
    @BindView(R2.id.add_cancel)
    TextView addCancel;
    @BindView(R2.id.add_commit)
    TextView addCommit;
    @BindView(R2.id.scoop_flowlayout)
    TagFlowLayout mTagFlowLayout;
    @BindView(R2.id.scoop_title)
    EditText scoopTitle;
    @BindView(R2.id.current_num)
    TextView currentNum;
    @BindView(R2.id.scoop_anonymous)
    ToggleButton scoopAnonymous;
    @BindView(R2.id.scoop_content)
    EditText scoopContent;
    @BindView(R2.id.scoop_picture)
    GridImageView mGridView;
    @BindView(R2.id.location)
    TextView mLocation;
    @BindView(R2.id.contact)
    EditText contact;
    @BindView(R2.id.rule)
    TextView rule;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R2.id.content_images)
    RecyclerView mContentRecyclerView;

    @BindView(R2.id.room_view)
    LinearLayout mRootLayout;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.column_title)
    TextView columnTitle;
    @BindView(R2.id.scoop_content_title)
    TextView scoopContentTitle;
    @BindView(R2.id.layout_one)
    LinearLayout layoutOne;
    @BindView(R2.id.scoop_type)
    LinearLayout scooptype;

    private int isPrivate = 0;
    private boolean addCommitEnalbe = true;
    private List<ScoopTopicBean> tagList;

    private List<LocalMedia> selectedList = new ArrayList<>();
    private List<LocalMedia> resultList = new ArrayList<>();
    private LocalMedia addMde;
    private UpTokenBean data;
    private String cAnonymous;
    private String cTitle;
    private String cContent;
    private String cAuthor;
    private int cPlateId;
    private String cCreator;
    private String cCreatorAvatar;
    private String cPhone;
    private String cAddress;


    private List<Integer> tagIndex;
    private Iterator<Integer> iterator;
    private List<String> list;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String path, address;

    private String[] locationChoose = {"是", "否"};
    private int mIndex = 0;

    private LoadingDialog.Builder builder;

    private RequestOptions options;

    private List<String> selectedPhotos;

    private ScoopAddPresenter mPresenter;

    private RecyclerViewAdatper mImageAdapter;

    private int topId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.black_40per));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

    }

    @Override
    protected int getContentView() {
        return R.layout.broke_activity_scoop_add_pic;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }


    @Override
    protected void init() {
        mPresenter = new ScoopAddPresenter(this);
        topId = getIntent().getIntExtra("topId", 0);
        if (topId == 0) {
            tagList = (List<ScoopTopicBean>) getIntent().getExtras().getSerializable("taglist");
            tagList.remove(0);
        }

        initView();
        setListeners();
    }

    @Override
    protected void setListener() {

    }

    /**
     * 初始化
     */
    private void initView() {
        mPresenter.getToken();
        if (CommonUtils.getInstance().getSite() == 174) {
            title.setText("添加");
            columnTitle.setText("类型");
            scoopTitle.setHint("标题");
            scoopContentTitle.setText("内容  (");
            rule.setText("《协议》");
        } else {
            title.setText("添加内容");
            columnTitle.setText("内容类型");
            scoopTitle.setHint("内容标题");
            scoopContentTitle.setText("内容  (");
            rule.setText("《问答协议》");
        }
        //添加最有一个图片
        addMde = new LocalMedia();
        addMde.setPath("1");
        selectedList.add(addMde);

        selectedPhotos = new ArrayList<>();
        selectedList = new ArrayList<>();
        //提交等待动画
        builder = new LoadingDialog.Builder(ScoopAddPictureActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);
//        builder.showProgress(true);

        //glide配置
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.cover_normal_default)
                .error(R.drawable.cover_normal_default)
                .priority(Priority.HIGH);


        //话题选择
        //最多选一个标签
        mTagFlowLayout.setMaxSelectCount(1);

        mTagFlowLayout.setAdapter(new TagAdapter<ScoopTopicBean>(tagList) {
            @Override
            public View getView(FlowLayout parent, int position, ScoopTopicBean tag) {
                TextView tv = (TextView) LayoutInflater.from(ScoopAddPictureActivity.this).inflate(R.layout.broke_item_scoop_add_tag,
                        mTagFlowLayout, false);
                tv.setText("#" + tag.getName() + "#");
                return tv;
            }
        });

        if (topId == 0) {
            scooptype.setVisibility(View.VISIBLE);
        } else {
            scooptype.setVisibility(View.GONE);
        }
        //--------------------------------------定位--------------------------------------
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(15000);

        mLocationOption.setInterval(2000);

        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        mContentRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mContentRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mContentRecyclerView.setAdapter(mImageAdapter = new RecyclerViewAdatper());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList.size() < 1 && selectedList.size() > 0) {

                } else {
                    selectedList.clear();
                    selectedList.addAll(resultList);
                }

                if (selectedList != null && selectedList.size() > 0) {
                    selectedPhotos.clear();
                    for (int i = 0; i < selectedList.size(); i++) {
                        LocalMedia media = selectedList.get(i);
                        if (media.isCut() && !media.isCompressed()) {
                            // 裁剪过
                            path = media.getCutPath();
                        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            path = media.getCompressPath();
                        } else {
                            // 原图地址
                            path = media.getPath();
                        }
                        selectedPhotos.add(path);
                    }
                }
                selectedList.add(addMde);
                mImageAdapter.notifyDataSetChanged();
                mContentRecyclerView.invalidate();
                break;
            default:
                break;
        }
    }


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    address = aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + aMapLocation.getAoiName() + aMapLocation.getBuildingId();
                    mLocation.setText(address);
                } else {
                    Toasty.normal(ScoopAddPictureActivity.this, "定位失败！", Toast.LENGTH_SHORT).show();
                    mLocation.setText("所在地址");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
            mLocationClient.stopLocation();
        }
    };

    /**
     * 监听
     */
    private void setListeners() {
        //是否公开
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.private_button) {
                    isPrivate = 1;
                } else if (checkedId == R.id.public_button) {
                    isPrivate = 0;
                }
            }
        });

        //协议
        rule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RulePopup rulePopup = new RulePopup(ScoopAddPictureActivity.this);
                rulePopup.setPopupWindowFullScreen(true);
                rulePopup.showPopupWindow();
            }
        });

        //取消
        addCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //提交
        addCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addCommitEnalbe) {
                    addCommitEnalbe = false;
                    builder.show();
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                setCommit();
                                judgeCommit();//提交判断
                            } else {
                                builder.dismiss();
                                RouterManager.routerLogin(ScoopAddPictureActivity.this, 0);
                                Toasty.normal(ScoopAddPictureActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                addCommitEnalbe = true;
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });

                }
            }
        });

        //坐标
        mLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(ScoopAddPictureActivity.this, 1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ScoopAddPictureActivity.this);
                        builder.setTitle("是否显示当前所在地理位置？");
                        builder.setSingleChoiceItems(locationChoose, mIndex, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mIndex = which;
                            }
                        });
                        builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ("是".equalsIgnoreCase(locationChoose[mIndex])) {
                                    mLocationClient.startLocation();
                                } else {
                                    mLocation.setText("所在地址");
                                }
                                dialog.dismiss();
                            }
                        }).show();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(ScoopAddPictureActivity.this);
                    }
                });
            }
        });

        //内容字数监听
        scoopContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentNum.setText(scoopContent.getText().toString().length() + "");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //标题
        scoopTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isEmpty(s.toString())) {
                    setCommit();
                } else {
                    resetCommit();
                }
            }
        });

        builder.getmDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });


    }

    /**
     * 提交判断
     */
    private void judgeCommit() {
        //判断标题
        cTitle = scoopTitle.getText().toString();
        if (StringUtils.isEmpty(cTitle)) {
            Toasty.normal(ScoopAddPictureActivity.this, "标题不能为空！", Toast.LENGTH_SHORT).show();
            resetCommit();
            builder.dismiss();
            addCommitEnalbe = true;
            return;
        }

        //判断内容
        cContent = scoopContent.getText().toString();
        if (StringUtils.isEmpty(cContent)) {
            cContent = "";
        }

        //判断内容类型
        if (topId != 0) {
            cPlateId = topId;
        } else {
            tagIndex = new ArrayList<>();
            iterator = mTagFlowLayout.getSelectedList().iterator();
            while (iterator.hasNext()) {
                tagIndex.add(iterator.next());
            }

            if (tagIndex.size() > 0) {
                cPlateId = tagList.get(tagIndex.get(0)).getId();
            } else {
                Toasty.normal(ScoopAddPictureActivity.this, "请选择类型！", Toast.LENGTH_SHORT).show();
                resetCommit();
                builder.dismiss();
                addCommitEnalbe = true;
                return;
            }
        }


        //判断图片
        if (selectedPhotos.size() > 0) {
            list = new ArrayList<>();
            list.addAll(selectedPhotos);
        }

        //判断联系方式
        cPhone = contact.getText().toString();
        if (StringUtils.isEmpty(cPhone)) {
            cPhone = "";
        }

        //判断地址
        cAddress = mLocation.getText().toString();
        if ("所在地址".equals(cAddress) || StringUtils.isEmpty(cAddress)) {
            cAddress = "";
        }

        String userName = CommonUtils.getInstance().getUserName();
        String headicon = CommonUtils.getInstance().getUserLogo();
        //用户信息
        cCreator = userName;
        cCreatorAvatar = headicon;
        String nickName = CommonUtils.getInstance().getNickName();
        cAuthor = nickName;

        //是否匿名
        if (scoopAnonymous.isChecked()) {
            cAnonymous = "0";
        } else {
            cAnonymous = "1";
        }

        //提交
        if (data != null) {
            mPresenter.commit(cAnonymous, cTitle, cContent, "0", cAuthor, cPlateId + "", cCreator, cCreatorAvatar, "", cPhone, cAddress, list, isPrivate, data.getUptoken(), data.getPrefix());
        } else {
            Toast.makeText(this, "token错误", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 提交失败
     *
     * @param msg
     */
    @Override
    public void commitError(String msg) {
        builder.dismiss();
        Toasty.normal(ScoopAddPictureActivity.this, msg, Toast.LENGTH_SHORT).show();
        addCommitEnalbe = true;
    }

    /**
     * 提交成功
     *
     * @param msg
     */
    @Override
    public void commitSuccess(String msg) {
        builder.dismiss();
        Toasty.normal(ScoopAddPictureActivity.this, msg, Toast.LENGTH_SHORT).show();
        addCommitEnalbe = true;
        finish();
    }

    @Override
    public void cancelCommit() {
        resetCommit();
        addCommitEnalbe = true;
    }

    /**
     * 设置上传进度
     *
     * @param progress
     */
    @Override
    public void setProgress(float progress) {
        int per = (int) (progress * 100);
        if (per % 1 == 0) {
            handler.sendEmptyMessage(per);
        }

    }

    @Override
    public void getTokenSuccess(UpTokenBean data) {
        this.data = data;
    }

    /**
     * 设置提交按钮
     */
    private void setCommit() {
        addCommit.setEnabled(false);
        addCommit.setTextColor(getResources().getColor(R.color.global_gray_lv2));
        addCommit.setBackgroundResource(R.drawable.scoop_commit_off);
    }

    /**
     * 恢复提交按钮
     */
    private void resetCommit() {
        addCommit.setEnabled(true);
        addCommit.setTextColor(getResources().getColor(R.color.global_base));
        addCommit.setBackgroundResource(R.drawable.scoop_commit_on);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        StatService.onResume(this);
        StatService.onPageStart(this, "添加图文内容");
        //umeng
        MobclickAgent.onPageStart("添加图文内容");
        MobclickAgent.onResume(this);


        if (selectedList.size() == 0) {
            selectedList.add(addMde);
            mImageAdapter.notifyDataSetChanged();
        } else {
            if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                selectedList.add(addMde);
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        StatService.onPause(this);
        StatService.onPageEnd(this, "添加图文内容");
        //umeng
        MobclickAgent.onPageEnd("添加图文内容");
        MobclickAgent.onPause(this);
    }


    /**
     * RecyclerViewAdatper
     */
    public class RecyclerViewAdatper extends RecyclerView.Adapter<ViewHolder> {

        RecyclerViewAdatper() {
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.broke_item_content_img_list, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            if (selectedList.get(position).getPath().endsWith("1")) {
                holder.deleteView.setVisibility(View.GONE);
                holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                holder.handleView.setOnTouchListener(null);
            } else {
                holder.deleteView.setVisibility(View.VISIBLE);
                holder.deleteView.setTag(position);
                holder.deleteView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                            selectedList.add(addMde);
                        }
                        int pos = (int) v.getTag();
                        selectedList.remove(pos);
                        mImageAdapter.notifyDataSetChanged();
                        mContentRecyclerView.invalidate();
                    }
                });
                if (position == selectedList.size() - 1) {
                    holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                    holder.handleView.setOnTouchListener(null);
                } else {
                    Glide.with(ScoopAddPictureActivity.this).load(selectedList.get(position).getPath()).into(holder.handleView);
                    holder.handleView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                                if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                                    selectedList.add(addMde);
                                }
                            }
                            return false;
                        }
                    });
                }
            }
        }

        @Override
        public int getItemCount() {
            return selectedList.size();
        }
    }


    /**
     * ViewHolder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView handleView;
        public ImageView deleteView;

        public ViewHolder(View itemView) {
            super(itemView);
            handleView = (ImageView) itemView.findViewById(R.id.content_img);
            deleteView = (ImageView) itemView.findViewById(R.id.image_delete);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (selectedList.size() == 0 || !selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                        selectedList.add(addMde);
                    }
                    if (getLayoutPosition() == selectedList.size() - 1) {
                        //弹出选择菜单
                        selectedList.remove(selectedList.size() - 1);
                        chooseMenu();
                    } else {

                        ArrayList<String> result = new ArrayList<>();
                        for (int i = 0; i < selectedList.size() - 1; i++) {
                            result.add(selectedList.get(i).getPath());
                        }
                        MNImageBrowser.showImageBrowser(ScoopAddPictureActivity.this, view, getLayoutPosition(), result);


                    }
                }
            });
        }


    }

    private void chooseMenu() {
        PictureSelector.create(ScoopAddPictureActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(false)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    private final Handler handler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<ScoopAddPictureActivity> mActivity;

        public MyHandler(ScoopAddPictureActivity activity) {
            mActivity = new WeakReference<ScoopAddPictureActivity>(activity);
        }


        @Override
        public void handleMessage(Message msg) {
            ScoopAddPictureActivity scoopAdd = mActivity.get();
            scoopAdd.builder.setProgress(msg.what);
        }

    }

}
